/**
 * 持仓管理
 * @author zhanghaitao(2021-03-011)
 */
import accounting from 'accounting';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { message, Tooltip } from 'antd';

import api from '../../api';
import config from '../../comps/business/tradingMarket/config';
import dictionaryConfig from '../../utils/dictionaryConfig';

export default {
  namespace: 'positionManageM',
  state: {},
  effects: {
    // 获取证券管理列表
    *getManageList({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.getManageList, payload);
      const columns = [
        {
          title: '日期',
          dataIndex: 'id.dataDt',
          key: 'id.dataDt',
          width: 120,
          render: (val) => {
            if (val) {
              return `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6)}`;
            }
          },
        },

        {
          title: '组合代码',
          dataIndex: 'combiCode',
          key: 'combiCode',
          width: 120,
        },
        {
          title: '组合名称',
          dataIndex: 'combiName',
          key: 'combiName',
          width: 120,
        },
        {
          title: '持仓类型',
          dataIndex: 'posType',
          key: 'posType',
          width: 100,
          render: (text) => {
            switch (text) {
              case 'ZQZC':
                return '证券资产';
              case 'ZQFZ':
                return '证券负债';
              default:
                return '--';
            }
          },
        },
        {
          title: '交易市场',
          dataIndex: 'id.exchangeCode',
          key: 'id.exchangeCode',
          width: 120,
          render: (_, record) => {
            const text = record?.id.exchangeCode;
            const findvalue = config.filter((item) => item.selfValue == text);
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            }
            return '--';
          },
        },
        {
          title: '证券代码',
          dataIndex: 'id.tradingcode',
          key: 'id.tradingcode',
          width: 120,
        },
        {
          title: '证券名称',
          dataIndex: 'secuabbr',
          key: 'secuabbr',
          width: 180,
        },
        {
          title: '交易属性',
          dataIndex: 'shortBlankSign',
          key: 'shortBlankSign',
          width: 80,
        },

        {
          title: '期初数量',
          dataIndex: 'initialAmount',
          key: 'initialAmount',
          type: 'number',
          width: 120,
          render: (text, record) => {
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), record.id.securityType == '2' ? 2 : 0);
          },
        },
        {
          title: '当前数量',
          dataIndex: 'currentAmount',
          key: 'currentAmount',
          type: 'number',
          width: 120,
          render: (text, record) => {
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), record.id.securityType == '2' ? 2 : 0);
          },
        },
        {
          title: '可用数量',
          dataIndex: 'availableAmount',
          key: 'availableAmount',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (['3', '4', '32', '33'].includes(record.id.securityType)) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), record.id.securityType == '2' ? 2 : 0);
          },
        },
        {
          title: '冻结数量',
          dataIndex: 'frozenAmount',
          key: 'frozenAmount',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (['3', '4', '5', '6', '32', '33'].includes(record.id.securityType)) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), record.id.securityType == '2' ? 2 : 0);
          },
        },
        {
          title: '解冻数量',
          dataIndex: 'thawAmount',
          key: 'thawAmount',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (['3', '4', '5', '6', '32', '33'].includes(record.id.securityType)) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), record.id.securityType == '2' ? 2 : 0);
          },
        },
        {
          title: '质押数量',
          dataIndex: 'pledgeAmount',
          key: 'pledgeAmount',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (['3', '4', '5', '6', '32', '33'].includes(record.id.securityType)) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), record.id.securityType == '2' ? 2 : 0);
          },
        },
        {
          title: (
            <span>
              成本价
              <Tooltip
                title={
                  <>
                    <div>期权的成本价展示的是单位成本与合约乘数相乘的结果;</div>
                    <div>期货的成本价未与合约乘数相乘;</div>
                    <div>非标（理财直融）成本价通过全价加权平均计算;</div>
                    <div>债券成本价通过净价加权平均计算。</div>
                  </>
                }
              >
                <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
              </Tooltip>
            </span>
          ),
          dataIndex: 'costPrice',
          key: 'costPrice',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (text === null || text === undefined) {
              return '--';
            }
            if (record.id.securityType == '3' || record.id.securityType == '5') {
              // 银行间质押式融资回购展示负数
              return `-${accounting.formatNumber(Number(text), 4)}`;
            }
            if (record.id.securityType == '32') {
              // 银行间买断式融资回购展示负数
              return `-${accounting.formatNumber(Number(text), 4)}`;
            }
            return accounting.formatNumber(Number(text), 4);
          },
        },
        // {
        //     title: '收益',
        //     dataIndex: 'profits',
        //     key: 'profits',
        //     type: 'money',
        //     toFixed: '2'
        // },

        {
          title: '资产类型',
          dataIndex: 'id.securityType',
          key: 'id.securityType',
          width: 100,
          render: (_, record) => {
            const text = record?.id?.securityType;
            if (['101', '201'].includes(text)) {
              // 信用股票 股票负债资产 全部展示股票
              return '股票';
            }
            const value = dictionaryConfig.holdType.filter((i) => i.value == text);
            if (value && value.length > 0) {
              return value[0].title;
            }
            return '--';
          },
        },
        {
          title: '昨日估值表价格',
          dataIndex: 'valuationPrice',
          key: 'valuationPrice',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (['3', '4', '5', '6', '32', '33'].includes(record.id.securityType)) {
              return '--';
            }
            if (text === null || text === undefined) {
              return '--';
            }
            return accounting.formatNumber(Number(text), 4);
          },
        },
        {
          title: '借贷数量',
          dataIndex: 'securityLendingAmount',
          key: 'securityLendingAmount',
          align: 'right',
          width: 120,
          render: (text, record) => {
            if (['3', '4', '5', '6', '32', '33'].includes(record.id.securityType)) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            return accounting.formatNumber(Number(text), 0);
          },
        },
        {
          title: '投资类型',
          dataIndex: 'investmentType',
          key: 'investmentType',
          width: 90,
        },
      ];
      if (res && res.success) {
        callback({
          pageInfo: {
            total: res.total,
          },
          dataSource: res.data,
          columns,
        });
      } else {
        message.error(res ? res.message || '获取列表失败' : '获取列表失败');
      }
    },

    // 获取证券冻结解冻列表
    *getUnfreezeList({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.getUnfreezeList, payload);
      const columns = [
        {
          title: '发生日期',
          dataIndex: 'dataDt',
          key: 'dataDt',
          width: 120,
          render: (val) => {
            if (val) {
              return `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6)}`;
            }
          },
        },

        {
          title: '组合代码',
          dataIndex: 'combiCode',
          key: 'combiCode',
          width: 120,
        },
        {
          title: '组合名称',
          dataIndex: 'combiName',
          key: 'combiName',
          width: 120,
        },
        {
          title: '交易市场',
          dataIndex: 'exchangeCode',
          key: 'exchangeCode',
          width: 120,
          render: (text) => {
            const findvalue = config.filter((item) => item.selfValue == text);
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            }
            return '--';
          },
        },
        {
          title: '证券代码',
          dataIndex: 'tradingcode',
          key: 'tradingcode',
          width: 120,
        },
        {
          title: '证券名称',
          dataIndex: 'secuabbr',
          key: 'secuabbr',
          width: 180,
        },

        {
          title: '交易属性',
          dataIndex: 'shortBlankSign',
          key: 'shortBlankSign',
          width: 80,
        },
        {
          title: '业务类别',
          dataIndex: 'operateType',
          key: 'operateType',
          width: 100,
          render: (text) => {
            if (text == 4) {
              return '冻结';
            } else if (text == 5) {
              return '解冻';
            } else if (text == '4_1') {
              return '取消冻结';
            } else if (text == '5_1') {
              return '取消解冻';
            }
          },
        },
        {
          title: '发生数量',
          dataIndex: 'amount',
          key: 'amount',
          type: 'number',
          toFixed: '0',
          width: 120,
        },
        {
          title: '投资类型',
          dataIndex: 'investmentType',
          key: 'investmentType',
          width: 100,
        },

        {
          title: '操作员',
          dataIndex: 'operateBy',
          key: 'operateBy',
          width: 120,
        },
      ];
      if (res && res.success) {
        callback({
          pageInfo: {
            total: res.total,
          },
          dataSource: res.data,
          columns,
        });
      } else {
        message.error(res.message || '获取列表失败');
      }
    },
    // 获取按钮组合权限
    *getJurisdiction({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.getJurisdiction, payload);

      if (res && res.code == 0) {
        callback({
          dataSource: res.data.dataSource,
        });
      }
    },

    // 证券调整
    *adjustSecurity({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.adjustSecurity, payload);
      if (res && res.success) {
        callback(true);
        message.success('调整成功，请稍后重新查询');
      } else {
        message.error(res.message || '调整失败');
      }
    },

    // 获取登录用户权限
    *getUser({ payload, callback }, { call }) {
      const response = yield call(api.user.queryCurrent, payload);
      if (response) {
        callback(response);
      }
    },

    // 新增持仓
    *addNew({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.addNew, payload);
      if (res && res.success) {
        callback(true);
        message.success('新增成功,请稍后重新查询');
      } else {
        message.error(res.message || '新增失败失败');
      }
    },

    // 获取划出证券代码
    *getTransfer({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.getTransfer, payload);
      if (res && res.success) {
        callback(res.data);
      }
    },

    // 划出证券
    *outSecurity({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.outSecurity, payload);
      if (res && res.success) {
        callback(true);
      }
    },

    // 划入证券
    *inSecurity({ payload, callback }, { call }) {
      const res = yield call(api.positionManage.inSecurity, payload);
      if (res && res.success) {
        callback(true);
        message.success('划转成功,请稍后重新查询');
      } else {
        message.error(res.message || '划转失败');
      }
    },
  },

  reducers: {
    updateData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {},
};
